'use strict';

exports.index = async ctx => {
  const { query } = ctx.request;
  let pageSize = 10;
  if (query.pageSize) pageSize = Number(query.pageSize);
  const where = {};
  const status = 'selling';
  const { titleLike, storeId, itemType } = query;
  if (titleLike) where.title = { [ctx.model.Op.like]: `%${titleLike}%` };
  if (storeId) where.storeId = storeId;
  if (itemType) where.itemType = itemType;
  if (status) where.status = status;
  const options = {
    limit: pageSize,
    offset: query.currentPage ? pageSize * (query.currentPage - 1) : 0,
    order: [
      [ 'order', 'DESC' ],
    ],
    where,
  };
  const {
    count: total, rows: list,
  } = await ctx.model.Item.findAndCountAll(options);
  ctx.body = {
    list,
    pagination: {
      total,
      pageSize,
      current: parseInt(query.currentPage, 10) || 1,
    },
  };
};

exports.show = async ctx => {
  const options = {
    include: [
      {
        model: ctx.model.ItemImage,
      },
    ],
  };
  const item = await ctx.model.Item.findByPk(ctx.params.id, options);
  if (item) {
    ctx.body = item;
  } else {
    ctx.status = 404;
  }
};
